<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { drawerFormSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { getMenuList, saveOrUpdateMenu } from '/@/api/system/menu/menu.api';

  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const isButton = (type) => type === 2;
      const menuType = ref(0);
      const attrs = useAttrs();
      const [
        registerForm,
        { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate },
      ] = useForm({
        labelWidth: 100,
        schemas: drawerFormSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        menuType.value = data?.record?.menuType;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        const treeData = await getMenuList();
        updateSchema([
          {
            field: 'parentId',
            componentProps: { treeData },
          },
          {
            field: 'name',
            label: isButton(unref(menuType)) ? '按钮/权限' : '菜单名称',
          },
        ]);
        // 无论新增还是编辑，都可以设置表单值
        if (typeof data.record === 'object') {
          let values = { ...data.record };
          setFieldsValue(values);
          onUrlChange(values.url);
        }
        //禁用表单
        // setProps({ disabled: !attrs.showFooter });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          //提交表单
          await saveOrUpdateMenu(values, unref(isUpdate));
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
        // try {
        //   const values = await validate();
        //   setDrawerProps({ confirmLoading: true });
        //   // TODO custom api
        //   console.log(values);
        //   closeDrawer();
        //   emit('success');
        // } finally {
        //   setDrawerProps({ confirmLoading: false });
        // }
      }
      /** url 变化时，动态设置组件名称placeholder */
      function onUrlChange(url) {
        let placeholder = '';
        let httpUrl = url;
        if (url != null && url != '') {
          if (url.startsWith('/')) {
            url = url.substring(1);
          }
          url = url.replaceAll('/', '-');
          // 特殊标记
          url = url.replaceAll(':', '@');
          placeholder = `${url}`;
        } else {
          placeholder = '请输入组件名称';
        }
        updateSchema([{ field: 'componentName', componentProps: { placeholder } }]);
        //update-begin---author:wangshuai ---date:20230204  for：[QQYUN-4058]菜单添加智能化处理------------
        if (httpUrl != null && httpUrl != '') {
          if (httpUrl.startsWith('http://') || httpUrl.startsWith('https://')) {
            setFieldsValue({ component: httpUrl });
          }
        }
        //update-end---author:wangshuai ---date:20230204  for：[QQYUN-4058]菜单添加智能化处理------------
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
